
export const generateThumbnail = async (file: File): Promise<any> => {
    // 使用 FileReader 读取文件
    const readFile = (file: File): Promise<string> => {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = (event) => {
                if (event.target?.result) {
                    resolve(event.target.result as string);
                } else {
                    reject(new Error('File read error'));
                }
            };
            reader.onerror = reject;
            reader.readAsDataURL(file);
        });
    };

    // 使用 Promise 封装图像加载
    const loadImage = (dataUrl: string): Promise<HTMLImageElement> => {
        return new Promise((resolve) => {
            const img = new Image();
            img.src = dataUrl;
            img.onload = () => resolve(img);
        });
    };

    // 读取文件
    const dataUrl = await readFile(file);

    // 加载图像
    const img = await loadImage(dataUrl);

    // 获取图片的原始宽高
    const originalWidth = img.width;
    const originalHeight = img.height;

    // 创建 Canvas 并绘制缩略图
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');

    if (!ctx) {
        throw new Error('Failed to get canvas context');
    }

    const targetSize = 120;
    let width, height;

    // 按比例调整缩略图大小
    if (originalWidth > originalHeight) {
        width = targetSize;
        height = (originalHeight / originalWidth) * targetSize;
    } else {
        width = (originalWidth / originalHeight) * targetSize;
        height = targetSize;
    }

    canvas.width = width;
    canvas.height = height;
    ctx.drawImage(img, 0, 0, width, height);

    // 将 Canvas 转换为 JPEG 格式，质量为 45%
    const jpegQuality = 0.45;
    const thumbnailDataUrl = canvas.toDataURL('image/jpeg', jpegQuality);

    // 返回 Base64 编码的缩略图数据以及原始图片的宽高
    return {
        base64edData: thumbnailDataUrl.replace(/^data:image\/jpeg;base64,/, ''),
        originalWidth,
        originalHeight
    };
};